import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:xsdk_flutter/xsdk/operation/x_constant_temp.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_flutter.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';
import 'package:open_filex/open_filex.dart';

typedef XFileReadTextCallback = void Function(String? text,List<String>? lines);



/*

https://pub-web.flutter-io.cn/packages/file_picker
https://pub-web.flutter-io.cn/packages/flutter_document_picker


void main() async {
  var config = File('config.txt');

  // Put the whole file in a single string.
  var stringContents = await config.readAsString();
  print('The file is ${stringContents.length} characters long.');

  // Put each line of the file into its own string.
  var lines = await config.readAsLines();
  print('The file is ${lines.length} lines long.');
}


void main() async {
  var config = File('config.txt');

  var contents = await config.readAsBytes();
  print('The file is ${contents.length} bytes long.');
}


void main() async {
  var config = File('config.txt');
  try {
    var contents = await config.readAsString();
    print(contents);
  } catch (e) {
    print(e);
  }
}


import 'dart:io';
import 'dart:convert';

void main() async {
  var config = File('config.txt');
  Stream<List<int>> inputStream = config.openRead();

  var lines = utf8.decoder.bind(inputStream).transform(const LineSplitter());
  try {
    await for (final line in lines) {
      print('Got ${line.length} characters from stream');
    }
    print('file is now closed');
  } catch (e) {
    print(e);
  }
}

var logFile = File('log.txt');
var sink = logFile.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
await sink.close();


var sink = logFile.openWrite(mode: FileMode.append);


void main() async {
  var dir = Directory('tmp');

  try {
    var dirList = dir.list();
    await for (final FileSystemEntity f in dirList) {
      if (f is File) {
        print('Found file ${f.path}');
      } else if (f is Directory) {
        print('Found dir ${f.path}');
      }
    }
  } catch (e) {
    print(e.toString());
  }
}



Directory	                      Android	iOS	Linux	macOS	Windows
Temporary	                        ✔️	  ✔️	  ✔️	  ✔️	  ✔️
Application Support	              ✔️	  ✔️	  ✔️	  ✔️	  ✔️
Application Documents	            ✔️	  ✔️	  ✔️	  ✔️	  ✔️
Application Library	              ❌️	  ✔️	  ❌️	  ✔️	  ❌️
External Storage	                ✔️	  ❌	  ❌	  ❌️	  ❌️
External Cache Directories	      ✔️	  ❌	  ❌	  ❌️	  ❌️
External Storage Directories	    ✔️	  ❌	  ❌	  ❌️	  ❌️
Downloads	                        ❌	  ❌	  ✔️	  ✔️	  ✔️


 */
class XFileUtils{

  //1.已在app中初始化,获得各平台通用路径
  static void init(){

    String system=XFlutterUtils.getSystemName();
    if('Other'!=system && 'Web'!=system){
      //Future<Directory> tempDirectory = getTemporaryDirectory();
      Future<Directory> appDocumentsDirectory = getApplicationDocumentsDirectory();
      appDocumentsDirectory.then((Directory value){
        String appDocumentsDirectoryPath=value.path;
        XLogUtils.printLog('---init appDocumentsDirectoryPath= $appDocumentsDirectoryPath');
        XTempData.appDocumentsDirectoryPath=appDocumentsDirectoryPath;
      });
    }

  }

  //读取文本,注意:调用此方法的外层方法,也需要定义async, var txt=await readFileText(filePath);
  static void readFileText(
      {
        required String filePath,
        required XFileReadTextCallback callback,
        bool isReadAsString=true,//读取全部
      }
      ){

    if(isReadAsString){
      //读取全部
      File(filePath)
          .readAsString()
          .then(
              (String value)
          {
            //XLogUtils.printLog('---read file=$value');
            callback(value,null);
          }
      );
    }else{
      //按行读取
      File(filePath)
          .readAsLines()
          .then(
              (List<String> lines)
          {
            callback(null,lines);
          }
      );
    }


  }

  static Future<dynamic> readFileText_sync(
      {
        required String filePath,
        bool isReadAsString=true,//读取全部
      }
      ) async {

    if(isReadAsString){
      //读取全部 返回 String
      return File(filePath).readAsString();
    }else{
      //按行读取 返回 List<String>
      return File(filePath).readAsLines();
    }

  }

  /*
  创建文件夹
  String path = XTempData.appDocumentsDirectoryPath;
  String folderPath='$path/folderNameXXX';
   */
  static Future<Directory> initFolderPath(String folderPath) async{

    Directory folder=Directory(folderPath);
    //判断是否存在
    bool isExists= folder.existsSync();
    if (!isExists) {
      folder=await folder.create(recursive: true);
    }

    return folder;

  }

  //文件是否存在
  static bool isFileExistsSync(String filePath){
    File file=File(filePath);
    return file.existsSync();
  }

  //写入
  static Future<File> writeToFile(
      String filePath,
      String data,
      {
        FileMode mode= FileMode.write, //默认覆盖,  FileMode.append末尾追加
      }
      ) async{

    Directory folder=Directory(Uri.parse(filePath).path).parent;
    //判断是否存在
    bool isExists= await folder.exists();
    if (!isExists) {
      folder=await folder.create(recursive: true);
    }
    //
    File file=File(filePath);


    return file.writeAsString(data,mode:mode);

  }


  //删除文件夹(包括内部的所有文件)
  static void deleteFolder(String folderPath) async{
    Directory folder=Directory(folderPath);
    //判断是否存在
    bool isExists= folder.existsSync();
    if (isExists) {
      folder.deleteSync(recursive:true);
    }
  }


  //删除文件
  static void deleteFile(String filePath) async{
    File file=File(filePath);
    //判断是否存在
    bool isExists= file.existsSync();
    if (isExists) {
      file.deleteSync(recursive:true);
    }

  }


  /*
  读取asset文件夹的文件
  https://docs.flutter.dev/ui/assets/assets-and-images#loading-text-assets
  把文件放入assets的txt文件夹中,在pubspec.yaml中添加:
  assets:
    - assets/txt/

  assetsFilePath='assets/txt/my_text.txt';
   */
  static Future<String> readAssetsTextFile(BuildContext context, String assetsFilePath) async {
    //使用全局 rootBundle 获取文本文件 Assets
    //return await rootBundle.loadString('');

    //可以使用 DefaultAssetBundle。建议这样做，因为它允许在运行时切换 Assets 包，这对多语言 Assets 很有用
    return await DefaultAssetBundle.of(context).loadString(assetsFilePath);
  }




  /*
  打开文件: ANDROID IOS LINUX MACOS WEB WINDOWS
  https://pub-web.flutter-io.cn/packages/open_filex/install
  dependencies:
    open_filex: ^4.4.0

  import 'package:open_filex/open_filex.dart';

  android:(不设置provider会报错,提示找不到方法)
  1.添加FileProvider:
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="xxx.xxx.xxxxx">
    <application>
        ...
        <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.fileProvider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:replace="android:authorities">
            <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/filepaths"
                    tools:replace="android:resource" />
        </provider>
    </application>
</manifest>


  2.furthermore add code below in your /android/app/src/main/res/xml/filepaths.xml
<paths>
    <external-path name="external-path" path="."/>
    <external-cache-path name="external-cache-path" path="."/>
    <external-files-path name="external-files-path" path="."/>
    <files-path name="files_path" path="."/>
    <cache-path name="cache-path" path="."/>
    <root-path name="root" path="."/>
</paths>


  android支持类型
  {
            {".3gp",    "video/3gpp"},
            {".torrent","application/x-bittorrent"},
            {".kml",    "application/vnd.google-earth.kml+xml"},
            {".gpx",    "application/gpx+xml"},
            {".csv",    "application/vnd.ms-excel"},
            {".apk",    "application/vnd.android.package-archive"},
            {".asf",    "video/x-ms-asf"},
            {".avi",    "video/x-msvideo"},
            {".bin",    "application/octet-stream"},
            {".bmp",    "image/bmp"},
            {".c",      "text/plain"},
            {".class",  "application/octet-stream"},
            {".conf",   "text/plain"},
            {".cpp",    "text/plain"},
            {".doc",    "application/msword"},
            {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls",    "application/vnd.ms-excel"},
            {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe",    "application/octet-stream"},
            {".gif",    "image/gif"},
            {".gtar",   "application/x-gtar"},
            {".gz",     "application/x-gzip"},
            {".h",      "text/plain"},
            {".htm",    "text/html"},
            {".html",   "text/html"},
            {".jar",    "application/java-archive"},
            {".java",   "text/plain"},
            {".jpeg",   "image/jpeg"},
            {".jpg",    "image/jpeg"},
            {".js",     "application/x-javascript"},
            {".log",    "text/plain"},
            {".m3u",    "audio/x-mpegurl"},
            {".m4a",    "audio/mp4a-latm"},
            {".m4b",    "audio/mp4a-latm"},
            {".m4p",    "audio/mp4a-latm"},
            {".m4u",    "video/vnd.mpegurl"},
            {".m4v",    "video/x-m4v"},
            {".mov",    "video/quicktime"},
            {".mp2",    "audio/x-mpeg"},
            {".mp3",    "audio/x-mpeg"},
            {".mp4",    "video/mp4"},
            {".mpc",    "application/vnd.mpohun.certificate"},
            {".mpe",    "video/mpeg"},
            {".mpeg",   "video/mpeg"},
            {".mpg",    "video/mpeg"},
            {".mpg4",   "video/mp4"},
            {".mpga",   "audio/mpeg"},
            {".msg",    "application/vnd.ms-outlook"},
            {".ogg",    "audio/ogg"},
            {".pdf",    "application/pdf"},
            {".png",    "image/png"},
            {".pps",    "application/vnd.ms-powerpoint"},
            {".ppt",    "application/vnd.ms-powerpoint"},
            {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop",   "text/plain"},
            {".rc",     "text/plain"},
            {".rmvb",   "audio/x-pn-realaudio"},
            {".rtf",    "application/rtf"},
            {".sh",     "text/plain"},
            {".tar",    "application/x-tar"},
            {".tgz",    "application/x-compressed"},
            {".txt",    "text/plain"},
            {".wav",    "audio/x-wav"},
            {".wma",    "audio/x-ms-wma"},
            {".wmv",    "audio/x-ms-wmv"},
            {".wps",    "application/vnd.ms-works"},
            {".xml",    "text/plain"},
            {".z",      "application/x-compress"},
            {".zip",    "application/x-zip-compressed"},

}

   */

  static void openFile(String filePath){
    OpenFilex.open(filePath);
  }



}
